//定义axios 实例
import router from '@/router';
import axios from 'axios'
import { ElMessage } from 'element-plus';
import { useTokenStore } from '@/stores/token';
import { useUserStore } from '@/stores/user';
import { ref } from 'vue';
//服务器路径
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR);
//返回axios 实例
const service = axios.create({
    //设置基础地址
    baseURL: 'http://localhost:8080'
    // baseURL: 'http://114.55.111.26:8080'
});
//axios的请求拦截器
service.interceptors.request.use(config => {
    //定义pinia
    const tokenStore = useTokenStore()
    //如果不是登录请求就要在请求头中添加token
    if(config.url.startsWith("/admin/")){
        config.headers.token = tokenStore.tokenStr;
    }
    if(config.url.startsWith("/emp/")){
        config.headers.token = tokenStore.tokenStr;
    }
    if(config.url.startsWith("/user/")){
        config.headers.token = tokenStore.tokenStr;
    }
    return config
}, error => {
    return Promise.reject(error);
})
//axios的响应拦截器
service.interceptors.response.use(resp =>{
    //刷新token
    const token = resp.headers.token;
    if (token){
        const tokenStore = useTokenStore();
        tokenStore.update(token);
    }
    return resp.data;
},error=>{
    const tokenStore = useTokenStore();
    const useStore = useUserStore();
    if(error.status == 403){
        ElMessage.error({
            message: "令牌错误请重新登录",
            duration: 1200,
            onClose: ()=>{
              //删除seesionstorage的token
              tokenStore.$reset();
              useStore.$reset();
              //跳转到登录页
              router.push("/login");
            }
        })
    }
})
//导出实例
export default service;